import { MessageBoxService, GrowlMessageType } from './../../components/messageBox';
import { Router } from '@angular/router';
import { PrintComponentService } from './templates/printcontainer.component';
import { PrinterManager } from './../../utils/print/printer/printManager';
import { StoreSvr } from './../../services/store';
import { Component, Output, EventEmitter, OnInit, Input } from '@angular/core';
@Component({
    selector: 'config-device',
    template: `
        <div class="flex-column config-container">
            <div class="title bg-darkgray" (click)="changeName('interfaceType')">
                <i class="material-icons icon">navigate_before</i>
                <span>配置设备</span>
            </div>
            <div class="config-content flex-row">
                <div class="config-detail">
                    <div class="config-item" *ngIf="isAddDevice">
                        <p>找到的可用设备：</p>
                        <md-select [(ngModel)]="selectedPrinter.deviceData">
                            <md-option *ngFor="let data of deviceData" [value]="data">{{data.productName}}</md-option>
                        </md-select>
                    </div>
                    <div class="flex-row edit-title border-bottom" *ngIf="!isAddDevice">
                        <img class="img-printer" src="./assets/img/devtype-receipt-printer.png" >
                        <div class="flex-column">
                            <p>{{selectedPrinter.deviceName }}</p>
                            <p>{{selectedPrinter.productName}}</p>
                        </div>
                    </div>
                    <div class="config-item">
                        <p>设备信息：</p>
                        <div class="device-info color-gray">
                            <p class="text-s">产品型号：{{selectedPrinter.productName}}</p>
                            <p class="text-s">品牌/厂商：{{selectedPrinter.manufacturer}}</p>
                            <p class="text-s">连接方式：{{selectedPrinter.type}}</p>
                            <button class="btn-test" (click)="testPrint()">打印测试</button>
                        </div>
                    </div>
                    <div class="config-item">
                        <p>设置设备友好名称：</p>
                        <input md-input type="text" [(ngModel)]="selectedPrinter.deviceName" name="deviceName">
                        <p class="text-desc">可根据设备的位置或者用途定义更容易识别的名字，例如柜台、发票（可选）。</p>
                    </div>
                    <div class="config-item">
                        <p>打印机指令：</p>
                        <md-select [(ngModel)]="selectedPrinter.instruction">
                            <md-option *ngFor="let item of instruction" [value]="item">{{item.name}}</md-option>
                        </md-select>
                    </div>
                    <div class="config-item">
                        <p>打印机宽度：</p>
                        <md-select [(ngModel)]="selectedPrinter.paperSize">
                            <md-option *ngFor="let item of pageSizes" [value]="item">{{item.label}}</md-option>
                        </md-select>
                        <p class="text-desc">根据打印机的类型正确选择相应的宽度。</p>
                    </div>
                    <div class="config-item">
                        <p>尾部走纸行数：</p>
                        <md-select [(ngModel)]="selectedPrinter.paperScrollRows">
                            <md-option *ngFor="let item of paperScrollRows" [value]="item">{{item.label}}</md-option>
                        </md-select>
                        <p class="text-desc">设置走纸行数可以调整小票打印完成后到出口空白走纸的距离，以便切纸刚好在打印完成的位置。</p>
                    </div>
                    <div class="config-item">
                        <p>设备扩展支持：</p>
                        <div class="device-info">
                            <md-checkbox [(ngModel)]="selectedPrinter.isCut">是否带切刀</md-checkbox>
                        </div>
                    </div>
                    <button *ngIf="isAddDevice" class="btn-primary btn-add-device margin-t-m" (click)="addDevice()">添加设备</button>
                    <button *ngIf="!isAddDevice" class="btn-primary btn-add-device margin-t-m" (click)="saveDeviceChange(selectedPrinter.id)">保存设置</button>
                </div>
                <div class="turn-container">
                    <div class="turn-page flex-column">
                        <span (click)="scroll('top')">
                            <i class="material-icons text-l">expand_less</i>
                        </span>
                        <span (click)="scroll('bottom')">
                            <i class="material-icons text-l">expand_more</i>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    `,
    styleUrls: ['./printer.component.scss']
})

export class ConfigDeviceComponent implements OnInit {
    @Output()
    changePageName: EventEmitter<any> = new EventEmitter<any>();
    @Output()
    getList: EventEmitter<any> = new EventEmitter<any>();

    @Input() selectedPrinter: SelectedPrinter;
    constructor(
        private storeSvr: StoreSvr,
        private printerManager: PrinterManager,
        private printComponentService: PrintComponentService,
        private route: Router
    ) { }

    // 是否新增设备 true:新增 false:编辑设备信息
    private isAddDevice = true;
    private deviceData: any = [];
    // 设备名称
    private deviceName: string = "";
    // 打印机指令
    private instruction: any = [];
    // 打印机宽度
    private pageSizes: any = [];
    // 打印机尾部走纸行数
    private paperScrollRows: any = [];
    // 是否带切刀
    private isCut: boolean = false;
    // 打印机类型
    private deviceType: string = "";
    // 打印机信息
    private printerInfo: any = {};
    async ngOnInit() {
        this.initPrinter();
    }

    changeName(name) {
        this.changePageName.emit(name);
    }

    scroll(dir) {
        let container = document.querySelector('.config-content');
        if (dir == 'top') {
            container.scrollTop = container.scrollTop - 100;
        }
        if (dir == 'bottom') {
            container.scrollTop = container.scrollTop + 100;
        }
    }

    // 初始化打印机
    async initPrinter() {
        if (!this.selectedPrinter) {
            this.selectedPrinter = <any>({
                //设备id
                id: "",
                //设备信息
                deviceInfo: {},
                // 打印机指令
                instruction: {},
                // 设备名称
                deviceName: "",
                //连接类型 "wifi"，"蓝牙"等
                type: "",
                //设备的ip地址
                address: "",
                //设备的制造商
                manufacturer: "",
                //设备的型号
                productName: "",
                // 是否带切刀
                isCut: false,
                // 打印机尾部走纸行数
                paperScrollRows: {},
                // 打印机宽度
                paperSize: {},
                // 是否启用
                isUse: true,
                // 是否连接
                isConnect: true,
                usage: "kitchen-expedition",
            });
        }
        let selectedPrinter = this.selectedPrinter;
        this.instruction = this.printerManager.instructionSets;
        this.paperScrollRows = this.printerManager.paperScrollRows;
        this.pageSizes = this.printerManager.selectPageSizes;
        this.deviceData = this.storeSvr.getDeviceData();
        this.deviceType = this.storeSvr.getDeviceType();
        if (selectedPrinter.id) {
            this.isAddDevice = false;
            this.selectedPrinter.instruction = this.instruction.find((ins) => {
                return ins.value == this.selectedPrinter.instruction.value;
            });
            this.selectedPrinter.paperSize = this.pageSizes.find((size) => {
                return size.value == this.selectedPrinter.paperSize.value;
            });
            this.selectedPrinter.paperScrollRows = this.paperScrollRows.find((rows) => {
                return rows.value == this.selectedPrinter.paperScrollRows.value;
            });
        } else {
            this.isAddDevice = true;
            this.selectedPrinter.instruction = this.instruction[0];
            this.selectedPrinter.paperScrollRows = this.paperScrollRows[3];
            this.selectedPrinter.paperSize = this.pageSizes[0];
            this.selectedPrinter.deviceData = this.deviceData[0];
            this.selectedPrinter.deviceInfo = this.selectedPrinter.deviceData.deviceInfo;
            this.selectedPrinter.deviceName = this.deviceType;
            this.selectedPrinter.type = this.selectedPrinter.deviceData.type;
            this.selectedPrinter.address = this.selectedPrinter.deviceData.address;
            this.selectedPrinter.manufacturer = this.selectedPrinter.deviceData.manufacturer;
            this.selectedPrinter.productName = this.selectedPrinter.deviceData.productName;
        }
    }

    setPrinterInfo() {
        let printers = this.printerManager.getAllDevices();
        let printerInfo = {
            //设备id
            id: new Date().getTime() + '',
            // 打印机指令
            instruction: this.selectedPrinter.instruction,
            // 设备数据
            deviceData: this.selectedPrinter.deviceData,
            //设备信息
            deviceInfo: this.selectedPrinter.deviceInfo,
            // 设备名称
            deviceName: this.selectedPrinter.deviceName,
            //连接类型 "wifi"，"蓝牙"等
            type: this.selectedPrinter.deviceData.type,
            //设备的ip地址
            address: this.selectedPrinter.deviceData.address,
            //设备的制造商
            manufacturer: this.selectedPrinter.deviceData.manufacturer,
            //设备的型号
            productName: this.selectedPrinter.deviceData.productName,
            // 尾部走纸行数
            paperScrollRows: this.selectedPrinter.paperScrollRows,
            // 打印机宽度
            paperSize: this.selectedPrinter.paperSize,
            // 是否带切刀
            isCut: this.selectedPrinter.isCut,
            // 是否启用
            isUse: this.selectedPrinter.isUse,
            isConnect: this.selectedPrinter.isConnect,
            usage: this.selectedPrinter.usage
        }
        return printerInfo;
    }

    // 添加设备
    async addDevice() {
        let printerInfo = this.setPrinterInfo();
        this.printerManager.addDevice(printerInfo);
        let info = await MessageBoxService.current.Growl(GrowlMessageType.Success, "", "添加设备成功");
        this.getPrinterList();
        this.changeName('deviceType');
        this.selectedPrinter = null;
    }

    // 修改设备信息
    async saveDeviceChange(id) {
        let printerInfo = this.setPrinterInfo();
        printerInfo.id = id;
        let result = await this.printerManager.updateDeviceById(printerInfo);
        if (result.status == 200) {
            let info = await MessageBoxService.current.Growl(GrowlMessageType.Success, "", result.msg);
            this.getPrinterList();
            this.changeName('addDevice');
        } else {
            let info = await MessageBoxService.current.Growl(GrowlMessageType.Error, "", result.msg);
        }
        this.selectedPrinter = null;
    }


    getPrinterList() {
        let printers = this.printerManager.getAllDevices();
        this.getList.emit(printers);
    }

    // 测试打印
    async testPrint() {
        MessageBoxService.current.Growl(GrowlMessageType.Info, "", "打印测试进行中");
        let type = this.storeSvr.getPrintType();
        if (!this.isAddDevice) {
            let printer = this.printerManager.getDeviceById(this.selectedPrinter.id);
            type = printer.type;
        }
        let selectedInfo = {
            deviceInfo: this.selectedPrinter.deviceInfo,
            instructionSet: this.selectedPrinter.instruction,
            autoCut: this.selectedPrinter.isCut,
            paperScrollRows: this.selectedPrinter.paperScrollRows,
            type: type,
            paperSize: this.selectedPrinter.paperSize
        }
        let printParams = {
            token: this.storeSvr.Token,
            store: this.storeSvr.CurrentStore,
            isTestPrint: true,
            printers: [selectedInfo]
        }
        let result: any = await this.printComponentService.show(printParams);
        let testResult = await this.printerManager.printHtml(result);
        if (testResult && testResult.data) {
            if (testResult.data.retCode == 0) {
                MessageBoxService.current.Growl(GrowlMessageType.Info, "", "打印测试成功");
            } else {
                let info = this.printerManager.errMsg(testResult.data);
                MessageBoxService.current.Growl(GrowlMessageType.Error, "", info);
            }
        } else {
            MessageBoxService.current.Growl(GrowlMessageType.Error, "", "打印测试失败");
        }

        console.log(testResult);
    }
}

export interface SelectedPrinter {
    //设备id
    id?: string;
    // 设备数据
    deviceData?;
    //设备信息
    deviceInfo;
    // 打印机指令
    instruction;
    // 设备名称
    deviceName?: string;
    //连接类型 "wifi"，"蓝牙"等
    type: string;
    //设备的ip地址
    address?: string
    //设备的制造商
    manufacturer: string;
    //设备的型号
    productName: string;
    // 是否带切刀
    isCut: boolean;
    // 打印机尾部走纸行数
    paperScrollRows;
    // 打印机宽度
    paperSize;
    // 是否启用
    isUse: boolean;
    // 是否连接
    isConnect: boolean;
    usage: string;
}